package com.huilian.iotbox.admin.security;

import com.huilian.iotbox.admin.service.UserRoleService;
import com.huilian.iotbox.admin.service.UserService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.enums.RoleEnum;
import com.huilian.iotbox.data.enums.UserStatusEnum;
import com.huilian.iotbox.data.po.User;
import com.huilian.iotbox.data.po.UserRole;
import com.huilian.iotbox.data.service.UserCommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;


/**
 * @author: 少凡
 * @Date 2018/3/4 8:17
 */
@Slf4j
@Component("userDetailsService")
public class AdminUserDetailsService implements UserDetailsService, SocialUserDetailsService {

    @Resource
    private UserService userService;
    @Autowired
    private UserCommonService userCommonService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("表单登录用户名:" + username);
        return buildUser(username);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        log.info("设计登录用户Id:" + userId);
        return buildUser(userId);
    }

    private SocialUserDetails buildUser(String username) {

        final Integer count = userCommonService.checkUserName(username, UserStatusEnum.WRITE_OFF.getCode());
        if (count == 0) {
            throw new RuntimeException(username + "账号未注册");
        } else if (count > 1) {
            throw new RuntimeException(username + "账号存在多个，请联系平台客服处理");
        }

        User user = userService.findUserByLoginUserName(username, UserStatusEnum.WRITE_OFF.getCode());

        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        user.setLastLoginTime(new Date());
        if (user.getLoginCount() == null) {
            user.setLoginCount(0);
        }
        userService.updateLoginUser(user);

        return new SocialUser(user.getId().toString(), user.getPassword(),
                enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
                AuthorityUtils.commaSeparatedStringToAuthorityList(""));
    }

}
